package com.dmzc.stage3.AtomicXXX;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicStampedReference;

/***
 * 测试AtomicStampReference
 */
public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        AtomicStampedReference<Integer> atomicRef =
                new AtomicStampedReference<>(100, 0);
        Thread t1 = new Thread() {
            @Override
            public void run() {
                try {
                    //睡眠两秒，保证下面的线程先执行
                    TimeUnit.SECONDS.sleep(2);
                    boolean success = atomicRef.compareAndSet(100, 101,
                            atomicRef.getStamp(), atomicRef.getStamp() + 1);
                    success = atomicRef.compareAndSet(101, 100,
                            atomicRef.getStamp(), atomicRef.getStamp() + 1);
                    int[] res = new int[1];
                    atomicRef.get(res);
                    System.out.println(res[0]);
                    System.out.println(success);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                try {
                    int stamp = atomicRef.getStamp();
                    System.out.println(stamp);
                    TimeUnit.SECONDS.sleep(2);
                    boolean success = atomicRef.compareAndSet(100, 101,
                            stamp, atomicRef.getStamp() + 1);
                    System.out.println(atomicRef.getReference());
                    System.out.println(success);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t1.start();
        t2.start();
        t1.join();
        t2.join();

    }
}
